<template>
  <div ref="containerRef" class="container" :style="{ height }"></div>
</template>
<script setup>
import { ref, onMounted, onBeforeUnmount } from "vue";
import { initEcharts, disposeEcharts, echarts } from "@/config/echartsUtil";
const containerRef = ref(null);
let myChart = null;
let intervalId = null;
const formatNumber = (val) => {
  return val;
};
defineProps({
  height: {
    type: String,
    default: "140px",
  },
});
const init = () => {
  const data = [
    {
      value: 18,
      name: "技术工匠",
    },
    {
      value: 20,
      name: "设计研发",
    },
    {
      value: 35,
      name: "智能制造",
    },
    {
      value: 20,
      name: "绿色生产",
    },
    {
      value: 7,
      name: "国际营销",
    },
  ];

  const option = {
    tooltip: {
      trigger: "item", //数据项图形触发，主要在散点图，饼图等无类目轴的图表中使用。
      triggerOn: "none",
    },
    legend: {
      icon: "roundRect", // 矩形（默认）
      orient: "vertical",
      left: "145",
      top: "middle",
      itemWidth: 10,
      itemHeight: 10,
      //   itemGap: 20,
      textStyle: {
        rich: {
          nameStyle: {
            fontSize: 14,
            color: "#000000",
            align: "left",
            width: 40,
            verticalAlign: "middle",
          },
          valueStyle: {
            fontSize: 14,
            fontWeight: "bold",
            color: "#000000",
            align: "right",
            width: 80,
            verticalAlign: "middle",
          },
        },
      },
      formatter: function (name) {
        let target = 0;
        for (let i = 0; i < data.length; i++) {
          if (data[i].name === name) {
            target = data[i].value;
            break;
          }
        }
        return (
          "{nameStyle|" +
          name +
          "} {valueStyle|" +
          formatNumber(target) +
          "%" +
          "}"
        );
      },
    },
    color: [
      new echarts.graphic.LinearGradient(0, 0, 0, 1, [
        { offset: 0, color: "#00FFCC" },
        { offset: 1, color: "#24DCF7" },
      ]),
      new echarts.graphic.LinearGradient(0, 0, 0, 1, [
        { offset: 0, color: "#FFC800" },
        { offset: 1, color: "#F77400" },
      ]),
      new echarts.graphic.LinearGradient(0, 0, 0, 1, [
        { offset: 0, color: "#CEFF23" },
        { offset: 1, color: "#1ADA63" },
      ]),
      new echarts.graphic.LinearGradient(0, 0, 0, 1, [
        { offset: 0, color: "#015EEA" },
        { offset: 1, color: "#00C0FA" },
      ]),
    ],
    series: [
      {
        name: "人才缺口分类",
        type: "pie",
        center: ["16%", "50%"], // 图表位置
        radius: ["80%", "92%"], // 环形饼图，中间留空放文本
        // 中间文本配置（仅显示这一个label）
        label: {
          show: false,
          color: "#000000",
          fontSize: 18,
          position: "center", // label 展示位置
          textAlign: "center",
          verticalAlign: "middle",
          padding: 0, // 清除默认内边距，避免挤压
          // 使用rich属性来定义不同的文本样式
          rich: {
            name: {
              fontSize: 16,
              color: "#000",
              align: "center",
              verticalAlign: "middle",
            },
            value: {
              fontSize: 24,
              fontWeight: "bold",
              color: "#000",
              align: "center",
              verticalAlign: "middle",
            },
            unit: {
              fontSize: 16,
              color: "#000", // 红色
              align: "center",
              verticalAlign: "middle",
            },
          },
          formatter: function (params) {
            return (
              "{name|" +
              params.name +
              "}\n{value|" +
              formatNumber(params.value) +
              "}{unit|%}"
            );
          },
        },
        // 这里控制的是悬停到某个扇形区域时悬浮显示的内容样式
        /*tooltip: {
              trigger: 'item',
              // formatter: "{a} <br/>{b}: <br/>{c}个 (占比:{d}%)",
              color: '#fff',
              formatter: "{a} <br/>{b}:{c}个",
            },*/
        // 这里控制的是环形图中间显示内容高亮状态的显示样式
        emphasis: {
          label: {
            show: true,
            fontSize: 18,
          },
        },
        labelLine: {
          show: false,
        },
        data: data,
      },
    ],
  };
  myChart = initEcharts(containerRef.value, option);
  //   myChart.clear();
  //   myChart.off("click");

  myChart.on("click", (params) => {
    // this.$emit("clickChart", params.name);
  });
  let currentIndex = 0;
  const startAutoHighlight = () => {
    if (intervalId) clearInterval(intervalId);

    intervalId = setInterval(() => {
      // 取消之前选中的项
      myChart.dispatchAction({
        type: "downplay",
        seriesIndex: 0,
        dataIndex: currentIndex,
      });

      // 更新索引
      currentIndex = (currentIndex + 1) % data.length;

      // 高亮当前项
      myChart.dispatchAction({
        type: "highlight",
        seriesIndex: 0,
        dataIndex: currentIndex,
      });
    }, 3000);
  };

  // 3. 监听鼠标事件，实现互斥
  myChart.on("mouseover", (params) => {
    // 鼠标 hover 时：暂停定时器 + 取消自动高亮
    if (intervalId) clearInterval(intervalId);
    console.log("hover", params);

    // 取消所有扇区的自动高亮，只保留鼠标 hover 的高亮
    myChart.dispatchAction({
      type: "cancelHighlight",
      seriesIndex: 0,
    });
    // myChart.dispatchAction({
    //   type: "downplay",
    //   seriesIndex: 0,
    //   dataIndex: currentIndex,
    // });

    // （可选）主动触发鼠标 hover 扇区的高亮（确保样式统一）
    // myChart.dispatchAction({
    //   type: "highlight",
    //   seriesIndex: 0,
    //   dataIndex: params.dataIndex,
    // });
  });

  myChart.on("mouseout", () => {
    // 鼠标离开时：恢复定时器 + 继续自动高亮
    startAutoHighlight();
  });

  // 4. 初始化启动自动高亮
  startAutoHighlight();
  myChart.dispatchAction({
    type: "highlight",
    seriesIndex: 0,
    dataIndex: 0,
  });
};
const resizeListener = () => {
  window.addEventListener("resize", () => {
    if (myChart && myChart.resize) {
      myChart.resize();
    }
  });
};
onBeforeUnmount(() => {
  //   销毁实例;

  disposeEcharts(myChart);
  clearInterval(intervalId);
});
onMounted(() => {
  init();
  resizeListener();
});
</script>
<style lang="less" scoped></style>
